﻿using System;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeWeb.Utility;
using Common;
using System.Globalization;

namespace ProjectDan.CRM.Views
{
    public partial class UploadFile : Microsoft.Practices.CompositeWeb.Web.UI.Page, IUploadFileView
    {
        private UploadFilePresenter _presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this._presenter.OnViewInitialized();
            }
            this._presenter.OnViewLoaded();
        }

        [CreateNew]
        public UploadFilePresenter Presenter
        {
            get
            {
                return this._presenter;
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                this._presenter = value;
                this._presenter.View = this;
            }
        }

        public event EventHandler<DataEventArgs<UploadedFile>> SaveUploadedFile;

        protected void OnSaveUploadedFile(UploadedFile uploadedFile)
        {
            var handler = SaveUploadedFile;

            if (handler != null)
            {
                handler(this, new DataEventArgs<UploadedFile>(uploadedFile));
            }
        }

        public void CompleteSaveUploadedFile(int newId)
        {
            Response.Redirect(string.Format(CultureInfo.InvariantCulture, "EditUploadedFile.aspx?File={0}", newId));
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);

            _presenter.ReleaseView();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            btnSave.Click += new EventHandler(btnSave_Click);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            OnSaveUploadedFile(new UploadedFile()
            {
                Description = Description,
                FilePath = System.IO.Path.GetFileName(fuFile.FileName),
                Name = Name,
                Tags = Tags,
                FileBytes = fuFile.FileBytes
            });
        }

        public string Name { get { return txtName.Text; } set { txtName.Text = value; } }

        public string Description { get { return txtDescription.Text; } set { txtDescription.Text = value; } }

        public string Tags { get { return txtTags.Text; } set { txtTags.Text = value; } }
    }
}

